/*
 * Licensed under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.submarine.transport.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import org.submarine.common.Constants;
import org.submarine.config.ConfigUtil;
import org.submarine.exchange.TransferObject;
import org.submarine.exchange.adapter.ExchangeAdapter;
import org.submarine.transport.Endpoint;
import org.submarine.transport.codec.NettyDecoder;
import org.submarine.transport.codec.NettyEncoder;
import org.submarine.util.NetUtil;

/**
 * 
 * @file org.submarine.transport.netty.NettyServer.java
 *
 * Netty服务
 * 
 * @author gaojian
 * @created 2013-8-17 下午11:12:17
 * @version 0.0.1
 * @since 0.0.1
 *
 */
public class NettyServer extends Endpoint {
	
	private Integer port = Integer.getInteger(ConfigUtil.getProperty("Constants.SERVERPORT_KEY"), Constants.DEFAULT_SERVERPORT);
	
	private ServerBootstrap serverBootstrap;
	
	private EventLoopGroup bossGroup;
	 
    private EventLoopGroup workerGroup;
	
	public NettyServer(ExchangeAdapter exchangeAdapter) {
		super(exchangeAdapter);
	}
	
	/* (non-Javadoc)
	 * @see org.submarine.startup.Endpoint#start()
	 */
	@Override
	public void start() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        try {
        	serverBootstrap = new ServerBootstrap();
        	serverBootstrap.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 65536)
             .childOption(ChannelOption.TCP_NODELAY, true)
             .handler(new LoggingHandler(LogLevel.INFO))
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast("decoder", new NettyDecoder(Constants.DEFAULT_CHARSET_NAME))
                     	.addLast("encoder", new NettyEncoder(Constants.DEFAULT_CHARSET_NAME))
                     	.addLast(
                             new LoggingHandler(LogLevel.INFO),
                             new NettyServerHandler());
                 }
             });

        	serverBootstrap.bind(NetUtil.getHost(), port).sync();
            System.out.println("Netty server started!");
        } catch (InterruptedException e) {
			e.printStackTrace();
        }
	}
	
	/* (non-Javadoc)
	 * @see org.submarine.startup.Endpoint#stop()
	 */
	@Override
	public void stop() {
		if (null != bossGroup) {
			bossGroup.shutdownGracefully();
		}
		if (null != workerGroup) {
			workerGroup.shutdownGracefully();
		}
	}

	class NettyServerHandler extends SimpleChannelInboundHandler<TransferObject> {

		@Override
		protected void channelRead0(ChannelHandlerContext ctx, TransferObject transferObject) throws Exception {
			//同步操作，接收并处理消息，之后返回
			processedMessageRecived(ctx, transferObject);
		}
		
	}
	
}
